package com.ruoyi.web.controller.mstn;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.mstnExcel.CsvUtils;
import com.ruoyi.common.utils.mstnExcel.ExcelUtils;
import com.ruoyi.system.domain.CSVCatalystsQualityEntry;
import com.ruoyi.system.domain.excelImport.MstnCatalystsImport;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysCatalystsQuality;
import com.ruoyi.system.service.ISysCatalystsQualityService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 催化剂质量检测Controller
 * 
 * @author ruoyi
 * @date 2025-07-11
 */
@RestController
@RequestMapping("/system/quality")
@Slf4j
public class SysCatalystsQualityController extends BaseController
{
    @Autowired
    private ISysCatalystsQualityService sysCatalystsQualityService;

    /**
     * 查询催化剂质量检测列表
     */
    @PreAuthorize("@ss.hasPermi('system:quality:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysCatalystsQuality sysCatalystsQuality)
    {
        startPage();
        List<SysCatalystsQuality> list = sysCatalystsQualityService.selectSysCatalystsQualityList(sysCatalystsQuality);
        return getDataTable(list);
    }

    /**
     * 导出催化剂质量检测列表
     */
    @PreAuthorize("@ss.hasPermi('system:quality:export')")
    @Log(title = "催化剂质量检测", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysCatalystsQuality sysCatalystsQuality)
    {
        List<SysCatalystsQuality> list = sysCatalystsQualityService.selectSysCatalystsQualityList(sysCatalystsQuality);
        ExcelUtil<SysCatalystsQuality> util = new ExcelUtil<SysCatalystsQuality>(SysCatalystsQuality.class);
        util.exportExcel(response, list, "催化剂质量检测数据");
    }

    /**
     * 获取催化剂质量检测详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:quality:query')")
    @GetMapping(value = "/{catalystsQualityId}")
    public AjaxResult getInfo(@PathVariable("catalystsQualityId") Long catalystsQualityId)
    {
        return success(sysCatalystsQualityService.selectSysCatalystsQualityByCatalystsQualityId(catalystsQualityId));
    }

    /**
     * 新增催化剂质量检测
     */
    @PreAuthorize("@ss.hasPermi('system:quality:add')")
    @Log(title = "催化剂质量检测", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysCatalystsQuality sysCatalystsQuality)
    {
        return toAjax(sysCatalystsQualityService.insertSysCatalystsQuality(sysCatalystsQuality));
    }

    /**
     * 修改催化剂质量检测
     */
    @PreAuthorize("@ss.hasPermi('system:quality:edit')")
    @Log(title = "催化剂质量检测", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysCatalystsQuality sysCatalystsQuality)
    {
        return toAjax(sysCatalystsQualityService.updateSysCatalystsQuality(sysCatalystsQuality));
    }

    /**
     * 删除催化剂质量检测
     */
    @PreAuthorize("@ss.hasPermi('system:quality:remove')")
    @Log(title = "催化剂质量检测", businessType = BusinessType.DELETE)
	@DeleteMapping("/{catalystsQualityIds}")
    public AjaxResult remove(@PathVariable Long[] catalystsQualityIds)
    {
        return toAjax(sysCatalystsQualityService.deleteSysCatalystsQualityByCatalystsQualityIds(catalystsQualityIds));
    }

    /**
     * 多文件上传
     */
    @PostMapping("/upload")
    @Anonymous
    public AjaxResult upload(List<MultipartFile> files) throws Exception
    {
        try
        {
            List<CSVCatalystsQualityEntry> allArray = new ArrayList<>();
            for (MultipartFile file : files) {
                List<CSVCatalystsQualityEntry> array = CsvUtils.read(file, CSVCatalystsQualityEntry.class);
                if (array != null) {
                    allArray.addAll(array);
                }
            }
            List<CSVCatalystsQualityEntry> checkArray = allArray.stream().filter(item -> item.getBatchNo() != null).collect(Collectors.toList());
            if (checkArray.size() > 0) {
                // check不存在的
                List<String> notExist = sysCatalystsQualityService.checkNotExist(checkArray);
                if (notExist.size() > 0) {
                    List<SysCatalystsQuality> list = allArray.stream()
                            .filter(item -> notExist.contains(item.getBatchNo()))
                            .map(item -> item.toCatalystsQuality()).collect(Collectors.toList());
                    sysCatalystsQualityService.insertSysCatalystsQualityList(list);
                }
                return success(allArray);
            }
            return error("出错了");

        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/export/excel")
    @Anonymous
    public void exportExcel(HttpServletResponse response, SysCatalystsQuality sysCatalystsQuality)
        throws IOException
    {
        List<SysCatalystsQuality> list = sysCatalystsQualityService.selectSysCatalystsQualityList(sysCatalystsQuality);
        Workbook workbook = sysCatalystsQualityService.export(list, sysCatalystsQuality.getExportType());
        try
        {
            String fileName = "report-" + DateUtils.getTime();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".xlsx\"");
            workbook.write(response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("导出Excel异常{}", e.getMessage());
        }
        finally
        {
            IOUtils.closeQuietly(workbook);
        }
    }
}
